<?php

namespace app\api\controller;

use app\BaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;

class Base extends BaseController
{
    public static $aid;

    /**
     * @return mixed
     */
    public static function getAid()
    {
        return self::$aid;
    }

    /**
     * @param mixed $aid
     */
    public static function setAid($aid): void
    {
        self::$aid = $aid;
    }
    protected function initialize()
    {
        parent::initialize(); // 调用父类的初始化方法
        $header = request()->header(); // 获取请求头部信息

        // 鉴权
        if (!isset($header['token']) || empty($header['token'])) {
            return json(['code' => 403, 'msg' => '请先登录'])->send();
        }

        // 获取token 判断token是否存在 是否能够解码token
        try {
            $jwt = new JWT();
            $info = $jwt::decode($header['token'], new Key('api123456', 'HS256'));
            Base::$aid = $info->aid;
        } catch (ExpiredException $e) {
            // Token 过期处理
            throw new \think\exception\HttpResponseException(json(['code' => 403, 'msg' => 'token已经过期,请重新登录']));
        } catch (\Exception $e) {
            // 其他异常处理（比如解码失败等）
            throw new \think\exception\HttpResponseException(json(['code' => 403, 'msg' => 'token无效，请重新登录']));
        }


    }


}
